package tm;

import java.util.ArrayList;
import java.util.List;

/**
 * @author haoly
 * @title Tape
 * @date 2025/4/23 11:14
 * @description 磁带类
 */
public class Tape {
    private List<Character> left;

    private Character middle;

    private List<Character> right;

    private Character blank;

    public Tape(List<Character> left, Character middle, List<Character> right, Character blank) {
        this.left = new ArrayList<>(left);
        this.middle = middle;
        this.right = new ArrayList<>(right);
        this.blank = blank;
    }

    @Override
    public String toString(){
        StringBuilder leftBuilder = new StringBuilder();
        // 避免使用 Stream 或 join 等语法糖，使用基础循环
        for (int i = 0; i < left.size(); i++) {
            leftBuilder.append(left.get(i));
        }

        StringBuilder rightBuilder = new StringBuilder();
        for (int i = 0; i < right.size(); i++) {
            rightBuilder.append(right.get(i));
        }
        return "#<Tape " + leftBuilder + "(" + middle + ")" + rightBuilder + ">";
    }

    public List<Character> getLeft() {
        return left;
    }

    public Character getMiddle() {
        return middle;
    }

    public List<Character> getRight() {
        return right;
    }

    public Character getBlank() {
        return blank;
    }

    public Tape write(Character character){
        return new Tape(left, character, right, blank);
    }

    public Tape moveHeadLeft(){
        List<Character> rightNew = new ArrayList<>(right);
        rightNew.add(0, middle);

        List<Character> leftNew = new ArrayList<>(left);
        Character middleNew = blank;
        if (!left.isEmpty()) {
            middleNew = leftNew.remove(leftNew.size()-1);
        }
        return new Tape(leftNew, middleNew, rightNew, blank);
    }

    public Tape moveHeadRight(){
        List<Character> leftNew = new ArrayList<>(left);
        leftNew.add(middle);
        List<Character> rightNew = new ArrayList<>(right);

        Character middileNew = blank;
        if (!right.isEmpty()) {
            middileNew = rightNew.remove(0);
        }

        return new Tape(leftNew, middileNew, rightNew, blank);
    }
}
